package br.com.fiap.beans;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpSession;

import br.com.fiap.dao.LoginDAO;
import br.com.fiap.entity.Cliente;
import br.com.fiap.entity.Login;
import br.com.fiap.enumeration.TipoUsuario;

@Named
@ManagedBean(name="auth")
@SessionScoped
public class LoginBean extends AbstractBeanAcessor implements Serializable {

	private static final long serialVersionUID = 2156716669934292152L;
	
	@Inject
	private LoginDAO loginDAO;
	
	private String login;
	private String senha;
	private MenuBean menuBean;
	
	public MenuBean getMenuBean() {
		return menuBean;
	}

	public void setMenuBean(MenuBean menuBean) {
		this.menuBean = menuBean;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getSenha() {
		return senha;
	}

	public void setSenha(String senha) {
		this.senha = senha;
	}

	public String cadastrar() {
		setRequest("isFromLogin", true);
		
		
		return "/cliente/cadastro-cliente";
	}
	
	public String login() {
		Login persistedLogin = loginDAO.findByName(this.getLogin());
		
		if(persistedLogin != null && persistedLogin.getSenha().equals(this.senha)){
			setSession("usuarioLogado", persistedLogin.getCliente());
			HttpSession session = getSession();
			
			MenuBean menuBean = TipoUsuario.populaRoles(TipoUsuario.getEnumByKey(persistedLogin.getCliente().getTipoUsuario()));
			getSession().setAttribute("menuBean", menuBean);
			
			setMenuBean((MenuBean) session.getAttribute("menuBean")) ;
			return "/cliente/menu";
		}else return "/cliente/login";
	}
	
}
